package com.lebang.controller.api.earned;

import com.alibaba.fastjson.JSONObject;
import com.lebang.aop.Sessionid;
import com.lebang.common.MemberLock;
import com.lebang.common.Require;
import com.lebang.common.ValidCode;
import com.lebang.component.RedisClient;
import com.lebang.domain.AppEarnRouseSort;
import com.lebang.domain.DownloadMemberRecord;
import com.lebang.domain.TaskRouse;
import com.lebang.entity.RequestHeaders;
import com.lebang.feign.HundredAwardsFeign;
import com.lebang.model.RequestUserInfo;
import com.lebang.model.back.Result;
import com.lebang.model.enums.buss.DownStatus;
import com.lebang.model.enums.buss.TaskCategory;
import com.lebang.service.*;
import com.lebang.service.earn.DownMemberCountConfigService;
import com.lebangweb.common.TextUtil;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: ljx
 * @Date: 2020/11/09
 * @Version 1.0
 */
@Api(tags = "百倍奖励")
@RestController
@RequestMapping("/hundred/awards")
public class HundredAwardsApi {
    @Autowired
    private HundredAwardsFeign feign;
    @Autowired
    private DownMemberCountConfigService downMemberCountConfigService;
    @Autowired
    private DownAppService downAppService;
    @Autowired
    private PointService pointService;
    @Autowired
    private MemberNoticeService memberNoticeService;
    @Autowired
    private CpaService cpaService;
    @Autowired
    private TaskRouseClickService taskRouseClickService;
    @Autowired
    private HundredAwardsService hundredAwardsService;
    @Autowired
    private AppEarnRouseSortService appEarnRouseSortService;
    @Autowired
    private MemberNewTaskService memberNewTaskService;
    @Autowired
    private RedisClient redisClient;


    /**
     * 百倍奖励入口金币配置
     *
     * @param request
     * @return
     */
    @Require
    @ApiOperation("百倍奖励入口金币配置")
    @GetMapping("/point/config")
    public JsonData pointConfig(HttpServletRequest request) {
        RequestUserInfo userInfo = new RequestUserInfo(request);
        return Callback.success("success", "查询成功", feign.pointConfig(userInfo).getData());
    }

    /**
     * 判断该次数是否进入特殊奖励
     *
     * @param request
     * @param goldId
     * @return
     */
    @Require
    @ApiOperation("判断该次数是否进入特殊奖励")
    @PostMapping("/get/status")
    public JsonData getStatus(HttpServletRequest request, @RequestParam("goldId") Integer goldId) {
        RequestUserInfo userInfo = new RequestUserInfo(request);
        return feign.getStatus(userInfo, goldId);
    }

    /**
     * 普通奖励领取
     */
    @Require
    @ApiOperation("普通奖励领取")
    @PostMapping("/pull")
    @MemberLock
    public JsonData pull(HttpServletRequest request, @RequestParam("goldId") Integer goldId, @RequestParam("pointRecordId") Long pointRecordId, Integer status) {
        if (TextUtil.isEmpty(pointRecordId)) {
            return Callback.fail("204", "参数错误");
        }
        if (TextUtil.isEmpty(status)) {
            status = 1;
        }
        RequestUserInfo userInfo = new RequestUserInfo(request);
        RequestHeaders headers = new RequestHeaders(request);
        Result<Integer> result = feign.pull(userInfo, goldId, pointRecordId, status);
        if (result.isSuccess()) {
            if (result.getData().equals(0)) {
                return Callback.success("success", "0倍奖励");
            }
            pointService.addPoint(userInfo.getMemberId(), result.getData(),
                    TaskCategory.HUNDRED_AWARDS_POINT, headers, "");
            memberNoticeService.addNoticeAndPush("百倍奖励", "百倍金币奖励" + result.getData() + "金币", headers.getUserid(), headers);
            return Callback.success("success", "领取成功");
        }
        return Callback.fail("fail", "领取失败");
    }

    /**
     * 博百倍奖励转盘
     *
     * @param request
     * @return
     */
    @Require
    @ApiOperation("博百倍奖励转盘")
    @PostMapping("/reward")
    public JsonData hundredReward(HttpServletRequest request, @RequestParam("pointRecordId") Long pointRecordId) {
        if (TextUtil.isEmpty(pointRecordId)) {
            return Callback.fail("204", "参数错误");
        }
        RequestUserInfo userInfo = new RequestUserInfo(request);
        RequestHeaders header = new RequestHeaders(request);
        //用户是否还有每日必赚次数
        int wall = downMemberCountConfigService.checkCountByMemberId(userInfo.getMemberId());
        //检测次数是否用完
        return feign.hundredReward(userInfo, pointRecordId, downAppService.checkPushV2(header, wall, userInfo.getAppStore()));
    }

    /**
     * 获取一个本次做的数据源
     *
     * @param request
     * @return
     */
    @ApiOperation("获取一个本次做的数据源")
    @Require
    //@Sessionid
    @PostMapping("/bus/pull")
    @MemberLock
    public JsonData busrecord(HttpServletRequest request) {
        int weight = 1;
        RequestHeaders header = new RequestHeaders(request);

        int version = Integer.parseInt(header.getVersion());
        if (version <= 0) {
            return Callback.fail("200", "版本错误！");
        }
        boolean todo = true;
        Integer status = null;

        int wall = downMemberCountConfigService.checkCountByMemberId(header.getUserid());

        //检测次数是否用完
        if (downAppService.checkPushV2(header, wall, header.getAppStore())) {
            todo = false;
            status=201;
        }
        //获取用户当前第几次
        int count = downAppService.getTodayCountV2(header.getUserid());
        JSONObject jsonObject = new JSONObject();
        String skdKey = "";
        int type = 0;
        TaskRouse rouse = null;
        AppEarnRouseSort appEarnRouseSort = appEarnRouseSortService.getByCount(count, header.getAppStore());
        if (appEarnRouseSort == null) {
            todo = false;
            status=202;
        } else {
            if (appEarnRouseSortService.check(appEarnRouseSort, version)) {
                if ("random".equals(appEarnRouseSort.getSdkKey())) {
                    rouse = downAppService.getRandomAllKeyNotZy(header.getAppStore(), version, header.getUserid());
                    if (rouse == null) {
                        todo = false;
                        status =203;
                    }
                    type = appEarnRouseSort.getType() == 2 ? downAppService.randomPullV2() : appEarnRouseSort.getType();
                } else {
                    skdKey = appEarnRouseSort.getSdkKey();
                    type = appEarnRouseSort.getType() == 2 ? downAppService.randomPullV2() : appEarnRouseSort.getType();
                    rouse = downAppService.selectByKey(skdKey);
                }
            } else {
                rouse = downAppService.getRandomAllKeyNotZy(header.getAppStore(), version,  header.getUserid());
                if (rouse == null) {
                    todo = false;
                    status =204;
                }
                type = downAppService.randomPullV2();
            }
        }
        DownloadMemberRecord record;
        if (rouse == null) {
            todo = false;
            status =205;
        } else {
            List<String> strings = new ArrayList<>();
            rouse = downAppService.checkSdkMax(rouse, header, strings);
        }
        if (rouse == null) {
            todo = false;
            status =206;
        }
        if (todo) {
            record = downAppService.pull(header.getUserid(), type, header, rouse);
            jsonObject.put("open_return", rouse.getOpenReturn());
            jsonObject.put("type", type);
            jsonObject.put("recordId", record.getId());
            jsonObject.put("time", record.getTime());
            jsonObject.put("sdk_key", record.getSdkKey());
            return Callback.success("206", "查询成功", jsonObject);
        } else {
            return Callback.fail(status.toString(), "查询失败");
        }
    }

    /**
     * 五十倍或百倍
     *
     * @param request
     * @param appName
     * @param pkgName
     * @return
     */
    @Require
    @ApiOperation("五十倍或百倍")
    @PostMapping("/ishundred")
    public JsonData isHundred(HttpServletRequest request,
                              @RequestParam("pointRecordId") Long pointRecordId,
                              @RequestParam("appName") String appName,
                              @RequestParam("pkgName") String pkgName,
                              Integer recordId, String sdkKey, Integer type, Integer downType, Integer status) {
        RequestUserInfo userInfo = new RequestUserInfo(request);
        if (TextUtil.isEmpty(pointRecordId)) {
            return Callback.fail("204", "参数错误");
        }
        if (TextUtil.isEmpty(appName) || TextUtil.isEmpty(pkgName) || TextUtil.isEmpty(recordId)) {
            //其他概率倍数
            return feign.putOff(userInfo, pointRecordId);
        }

        DownloadMemberRecord record = downAppService.selectByRecordId(recordId);
        if (record == null) {
            return Callback.fail("204", "任务不存在");
        }
        if (cpaService.getZyData().equals(record.getSdkKey())) {
            return Callback.fail("204", "任务错误");
        }
        if (!record.getMemberId().equals(userInfo.getMemberId())) {
            return Callback.fail("204", "任务不存在");
        }
        if (!record.getStatus().equals(DownStatus.WAIT_PUSH.getIndex())) {
            return Callback.fail("204", "任务不存在");
        }
        if (TextUtil.isEmpty(status)) {
            status = 1;
        }
        if (!TextUtil.isEmpty(sdkKey)) {
            if ("TZSH".equals(sdkKey) && TextUtil.isEmpty(record.getType())) {
                record.setSdkKey(sdkKey);
                record.setType(type);
            }
        }
        if (!TextUtil.isEmpty(downType)) {
            record.setDownType(downType);
        }
        int num = hundredAwardsService.updateRecord(userInfo, status, record, appName, pkgName);
        if (num == 1) {
            return Callback.success("201", "百倍奖励");
        } else {
            //二次
            return Callback.success("202", "五十倍奖励");
        }
    }


    /**
     * 下载完成时间
     */
    @Require
    @ApiOperation("下载完成时间")
    @PostMapping("/finish/time")
    public JsonData finishTime(HttpServletRequest request, @ApiParam(name = "记录id") @RequestParam("recordId") Integer recordId) {
        RequestHeaders requestHeaders = new RequestHeaders(request);
        if (recordId == null) {
            return Callback.fail("200", "任务id为空");
        }
        DownloadMemberRecord record = downAppService.selectByRecordId(recordId);
        if (record == null) {
            return Callback.fail("200", "任务不存在");
        }
        if (!record.getMemberId().equals(requestHeaders.getUserid())) {
            return Callback.fail("200", "任务不存在");
        }
        if (!TextUtil.isEmpty(record.getEndTime())) {
            return Callback.success("200", "已存在");
        }
        record.setEndTime(LocalDateTime.now());
        record.setIsOpen(1);
        record = downAppService.updateRecord(record);
        return Callback.success("success", "操作成功", record.getEndTime());
    }

    @Sessionid
    @Require
    @PostMapping("/bus/push")
    @ApiOperation("提交任务")
    @ValidCode
    @MemberLock
    public JsonData buspush(HttpServletRequest request,
                            @RequestParam("type") Integer type,
                            @RequestParam("pointRecordId") Long pointRecordId,
                            @ApiParam(name = "任务id") Long recordId,
                            @ApiParam(name = "图标") String icon,
                            Integer category,String adId) {
        if (recordId == null || type == null || category == null) {
            return Callback.fail("201", "参数非法");
        }
        RequestUserInfo userInfo = new RequestUserInfo(request);
        RequestHeaders header = new RequestHeaders(request);
        String memberId = header.getUserid();
        DownloadMemberRecord record = downAppService.selectByRecordId(recordId);
        if (record == null) {
            return Callback.fail("201", "任务不存在");
        }
        boolean isZy = record.getSdkKey().equals(cpaService.getZyData());

        int wall = downMemberCountConfigService.checkCountByMemberId(header.getUserid());
        if (downAppService.checkPushV2(header, wall, header.getAppStore()) && !isZy) {
            return Callback.fail("207", "今日暂无任务，请明日再来");
        }
        if (!record.getMemberId().equals(memberId)) {
            return Callback.fail("202", "任务不存在.");
        }
        if (record.getEndTime() == null) {
            return Callback.fail("203", "任务不存在..");
        }
        if (!record.getStatus().equals(DownStatus.WAIT_PUSH.getIndex())) {
            return Callback.fail("204", "任务不存在...");
        }
        //获取体验秒数
        Long until = record.getEndTime().until(LocalDateTime.now(), ChronoUnit.SECONDS);
        Result<Integer> result = feign.getAwardsPoint(userInfo, type, pointRecordId, until);
        if (result.isSuccess()) {
            record.setModifyTime(LocalDateTime.now());
            record.setMoney(result.getData());
            record.setTime(until.intValue());
            record = downAppService.updateRecord(record);

            downAppService.addDownCount(record);
            downAppService.push(recordId, category, header, icon,adId);
            //今日个人次数+1
            downAppService.addV2(header, record.getSdkKey());
            int success = downAppService.getSuccessByMemberId(record.getMemberId());
            //每日必赚新手任务完成
            memberNewTaskService.addMrbz(success, record.getMemberId());
            //清除签到列表缓存
            redisClient.hdel(downAppService.getClickCacheKey(), memberId);
            //今日总次数+1
            downAppService.addSuccessCount();
            downAppService.checkHasRecord(header);
            return Callback.success("success", "领取成功", result.getData());
        }
        return Callback.success("success", "领取失败");
    }


    /**
     * 百倍奖励任务详情
     */
    @Require
    @ApiOperation("百倍奖励任务详情")
    @PostMapping("/task/details")
    public JsonData initRecord(HttpServletRequest request,
                               @RequestParam(name = "type",required = false) Integer type, String sdkKey,
                               @RequestParam(value = "recordId",required = false) Integer recordId,
                               @RequestParam(value = "pointRecordId",required = false) Long pointRecordId) {
        if (TextUtil.isEmpty(sdkKey)) {
            return Callback.fail("fail", "查询失败");
        }
        RequestUserInfo userInfo = new RequestUserInfo(request);
        Long id = downAppService.selectByKey(sdkKey).getId();
        TaskRouse taskRouse = downAppService.selectTaskRouse(id);
        if (taskRouse.getHasClick().equals(0)) {
            //未开启签到
            return Callback.fail("fail", "查询失败");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("totalPoint", taskRouseClickService.findListByRouseId(taskRouse.getId()));
        if (recordId != null && pointRecordId !=null){
            DownloadMemberRecord record = downAppService.selectByRecordId(recordId);
            feign.hasFirst(userInfo,record.getHasFirst(),pointRecordId);
        }
        return Callback.success("success", "查询成功", jsonObject);
    }

    /**
     * 百倍奖励进度配置
     */
    @Require
    @ApiOperation("百倍奖励进度配置")
    @PostMapping("/double/config")
    public JsonData doubleConfig(HttpServletRequest request, @RequestParam("type") Integer type) {
        RequestUserInfo userInfo = new RequestUserInfo(request);
        return feign.doubleConfig(userInfo, type);
    }

    /**
     * 放弃百倍奖励
     *
     * @param request
     * @return
     */
    @Require
    @ApiOperation("放弃百倍奖励")
    @PostMapping("/giveup")
    public JsonData giveUp(HttpServletRequest request, @RequestParam("pointRecordId") Long pointRecordId,@ApiParam(name = "记录id") @RequestParam(name = "recordId",required = false) Integer recordId) {
        RequestUserInfo userInfo = new RequestUserInfo(request);
        if (recordId != null) {
            DownloadMemberRecord record = downAppService.selectByRecordId(recordId);
            if (record == null) {
                return Callback.fail("200", "任务不存在");
            }
            record.setStatus(DownStatus.RELSE.getIndex());
            downAppService.updateRecord(record);
        }
        return feign.giveUp(userInfo, pointRecordId);
    }


    /**
     * 获取今日用户收益
     *
     * @return
     */
    @Require
    @ApiOperation("获取今日用户收益")
    @PostMapping("/get/todayMoney")
    public JsonData getTodayMoney(HttpServletRequest request) {
        RequestUserInfo userInfo = new RequestUserInfo(request);
        return Callback.success("success", "查询成功", hundredAwardsService.getTodayMoney(userInfo.getMemberId()));
    }
}
